﻿package com.snakedickgames.common
{
    import com.pblabs.engine.debug.Logger;
    import com.pblabs.engine.components.TickedComponent;
    import com.pblabs.engine.entity.PropertyReference;
    import com.pblabs.engine.PBE;
    import com.pblabs.engine.core.ProcessManager;
    import flash.geom.Point;
    import flash.utils.Dictionary;
        
    
    public class EntityEmitter extends TickedComponent
    {
        public var enabled:Boolean = true;
        public var emissionDelay:Number = 1000.0;
        public var spawnTemplate:String;
        public var positionProperty:PropertyReference;
        public var makeParams:Object;
        public var numSpawns:int = -1; // -1 for unlimited spawns, make sure emissionDelay greater than zero 
        
        override public function onTick(deltaTime:Number):void
        {
            super.onTick(deltaTime);
            var timeNow:Number = PBE.processManager.virtualTime;
            // allow for multiple spawns per tick
            while (enabled && _nextSpawnTime <= timeNow && numSpawns != 0)
            {
                emitEntity();
                _nextSpawnTime = timeNow + emissionDelay;
            }
        }
        
        public function emitEntity():void 
        {
            if (numSpawns == 0)
                return;
                
            var spawnPoint:Point = owner.getProperty(positionProperty) as Point;
            if (!spawnPoint)
                spawnPoint = new Point(0, 0);
            if (makeParams == null)
                makeParams = { };
            makeParams["@Spatial.position"] = spawnPoint;
            PBE.makeEntity(spawnTemplate, makeParams);
            
            if (numSpawns != -1)
                numSpawns--;
        }
        
        public function start():void
        {
            enabled = true;
            _nextSpawnTime = PBE.processManager.virtualTime;
        }
        
        public function stop():void
        {
            enabled = false;
        }
        
        protected override function onAdd():void
        {
            super.onAdd();
            owner.eventDispatcher.addEventListener(FIRE_EVENT, _onTriggered);
        }
      
        protected override function onRemove():void
        {
            owner.eventDispatcher.removeEventListener(FIRE_EVENT, _onTriggered);            
            super.onRemove();
        }
        
        protected function _onTriggered():void
        {
            emitEntity();
        }
        
        private var _nextSpawnTime : Number = 0.0;
        
        static public var FIRE_EVENT:String = "Fire";
    }

}